//
//  HXCycleImage.m
//  Taste
//
//  Created by 徐昊 on 16/8/31.
//  Copyright © 2016年 徐昊. All rights reserved.
//

#import "HXCycleImage.h"
#import "HXMacro.h"
#import "UIImageView+WebCache.h"
#import "HomepageModel.h"
#import "Res.h"
#import "Content.h"
#import "NSString+Vali.h"
#import "ZWYNetTool.h"
#import "UIImage+Transparent.h"
#import "HomepageViewController.h"
#import "HomePageSearchViewController.h"
#import "ShowDetailViewController.h"
#import "PersonViewController.h"
#import "HomePageDetailViewController.h"
#import "MasterCookBookViewController.h"
#import "HomepageViewController.h"

#define kCycleCollectionViewCellName @"CycleCollectionViewCellNameReuse"
@interface HXCycleImage ()<UICollectionViewDataSource, UICollectionViewDelegate>
@property (nonatomic, strong) UICollectionView *cycleCollectionView;
@property (nonatomic, strong) UICollectionViewFlowLayout *layout;
@property (nonatomic, strong) UIPageControl *pageControl;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) UILabel *text;
@property (nonatomic, strong) UIImageView *image;
@end

@implementation HXCycleImage

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor redColor];
        [self setUp];
    }
    return self;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        self.backgroundColor = [UIColor redColor];
        [self setUp];
    }
    return self;
}
- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    //    [self.datasource collectionViewCell:self.cell];
}
- (void)setUp {
    [self createCollectionView];
    [self createPageControl];
    [self createTimer];
    [self createView];
}
- (void)createCollectionView {
    _layout = [[UICollectionViewFlowLayout alloc] init];
    _layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    _layout.minimumLineSpacing = 0;
    _layout.minimumInteritemSpacing = 0;
    _cycleCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout: _layout];
    _cycleCollectionView.delegate = self;
    _cycleCollectionView.dataSource = self;
    _cycleCollectionView.pagingEnabled = YES;
    
    [_cycleCollectionView registerClass:[HXCycleImageCell class] forCellWithReuseIdentifier:kCycleCollectionViewCellName];
    
    _cycleCollectionView.showsHorizontalScrollIndicator = NO;
    [self addSubview:_cycleCollectionView];
    _cycleCollectionView.backgroundColor = [UIColor whiteColor];
}
- (void)setTopimg:(NSMutableArray<Content *> *)topimg {
    _topimg = topimg;
    id first = _topimg.firstObject;
    id last = _topimg.lastObject;
    [_topimg addObject:first];
    [_topimg insertObject:last atIndex:0];
    [_cycleCollectionView reloadData];
}
#pragma mark - CollectionView Datasource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    _pageControl.numberOfPages = _topimg.count - 2;
    return _topimg.count;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    HXCycleImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kCycleCollectionViewCellName forIndexPath:indexPath];
    // 网络请求图片
    [cell.cycleImage sd_setImageWithURL:[NSURL URLWithString:[NSString imageWebWithStr:self.topimg[indexPath.row].pic]] placeholderImage:[UIImage imageNamed:@"IMG_Universal_Placeholder"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
    }];
    cell.label.text = self.topimg[indexPath.row].title;
    cell.video.alpha = 0;
    if ([self.topimg[indexPath.row].video isKindOfClass:[NSString class]]) {
        
    } else {

        if ([self.topimg[indexPath.row].video isEqual:@(1)]) {
            cell.video.alpha = 1;
        }
    }
    
    return cell;
}
#pragma mark - CreatePageControl
- (void)createPageControl {
    self.pageControl = [[UIPageControl alloc] initWithFrame:CGRectZero];
    _pageControl.currentPageIndicatorTintColor = [UIColor whiteColor];
    _pageControl.pageIndicatorTintColor = [UIColor lightGrayColor];
    //    _pageControl.backgroundColor = [UIColor redColor];
    [self addSubview:_pageControl];
    
}
#pragma mark - CreateTimer
- (void)createTimer {
    // 这个创建NSTimer的方式仅仅是创建, 并没有加在runLoop中, 所以需要手动加入RunLoop中
    //    NSTimer *timer = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(nextPage) userInfo:nil repeats:YES];
    
    //    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    // 创建一个timer, 并添加到loop中
    // NSRunLoopCommonModes 和NSDefaultRunLoopMode
    // 后者代表默认状态, scheduledTimerWithTimeInterval添加默认状态
    // 前者为多种状态, 包含默认 及 滚动
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(nextPage) userInfo:nil repeats:YES];
    self.timer = timer;
    
}
#pragma mark - CreateView
- (void)createView {
    _image = [[UIImageView alloc] init];
    _image.image = [UIImage imageToTransparent:[UIImage imageNamed:@"LZImg_FirstPage_Button_Search"]];
    _text = [[UILabel alloc] init];
    _text.text = @"餐厅精选";
    _text.textColor = [UIColor whiteColor];
    [self addSubview:_image];
    [_image addSubview:_text];
    _image.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(click:)];
    [_image addGestureRecognizer:tap];
}
- (void)click:(UITapGestureRecognizer *)tap {
    HomepageViewController *vc = (HomepageViewController *)self.nextResponder.nextResponder.nextResponder   ;
    HomePageSearchViewController *search = [[HomePageSearchViewController alloc] init];
    [vc.navigationController pushViewController:search animated:YES];
    
}
- (void)nextPage {
    CGFloat totaloffset = _cycleCollectionView.contentOffset.x + self.bounds.size.width;
    [_cycleCollectionView setContentOffset:CGPointMake(totaloffset, 0) animated:YES];
    if (totaloffset == (_topimg.count - 1) * self.bounds.size.width) {
        _cycleCollectionView.contentOffset = CGPointZero;
    }
    _pageControl.currentPage = (_cycleCollectionView.contentOffset.x + self.bounds.size.width) / self.bounds.size.width - 1;
}
- (void)removeTimer {
    // 取消timer
    [self.timer invalidate];
    self.timer = nil;
}
- (void)layoutSubviews {
    [super layoutSubviews];
    _cycleCollectionView.frame = self.bounds;
    _layout.itemSize = self.bounds.size;
    [_cycleCollectionView setContentOffset:CGPointMake(SCREEN_WIDTH, 0)];
    
    _pageControl.frame = CGRectMake(0, 0, 100, 20);
    _pageControl.center = CGPointMake(SCREEN_WIDTH - 50, self.bounds.size.height - 20);
    
    
    _label.frame = CGRectMake(0, 0, SCREEN_WIDTH, 50);
    _label.center = CGPointMake(SCREEN_WIDTH / 2, 20);
    
    _image.frame = CGRectMake(0, 0, SCREEN_WIDTH, 40);
    _text.frame = CGRectMake(20, 0, 100, 40);
    
}
#pragma mark - 点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0 || indexPath.row == 5) {
        
    }
    if ([_topimg[indexPath.row].cid2 isEqualToString:@"3"]) {
        ShowDetailViewController *vc = [[ShowDetailViewController alloc] init];
        vc.idString = _topimg[indexPath.row].sid;
        HomepageViewController *HomeVC = (HomepageViewController *)self.nextResponder.nextResponder.nextResponder;
        [HomeVC.navigationController pushViewController:vc animated:YES];
    }
    if ([_topimg[indexPath.row].cid2 isEqualToString:@"16"]) {
        PersonViewController *vc = [[PersonViewController alloc] init];
        vc.numString = _topimg[indexPath.row].sid;
        HomepageViewController *HomeVC = (HomepageViewController *)self.nextResponder.nextResponder.nextResponder;
        [HomeVC.navigationController pushViewController:vc animated:YES];
    }
    if ([_topimg[indexPath.row].cid2 isEqualToString:@"1"]) {
        HomePageDetailViewController *vc = [[HomePageDetailViewController alloc] init];
        vc.numString = _topimg[indexPath.row].sid;
        HomepageViewController *HomeVC = (HomepageViewController *)self.nextResponder.nextResponder.nextResponder;
        [HomeVC.navigationController pushViewController:vc animated:YES];
    }
    if ([_topimg[indexPath.row].cid2 isEqualToString:@"14"]) {
        MasterCookBookViewController *vc = [[MasterCookBookViewController alloc] init];
        vc.numString = _topimg[indexPath.row].sid;
        HomepageViewController *HomeVC = (HomepageViewController *)self.nextResponder.nextResponder.nextResponder;
        [HomeVC.navigationController pushViewController:vc animated:YES];
    }
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self removeTimer];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [self createTimer];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    //#warning 直接判断等与0有啥问题
    if (scrollView.contentOffset.x <= _cycleCollectionView.bounds.size.width / 2.0) {
        [_cycleCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:(_topimg.count - 2) inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    } else if (scrollView.contentOffset.x >= _cycleCollectionView.bounds.size.width * (_topimg.count - 1) - 1) {
        [_cycleCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:1 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    }
    _pageControl.currentPage = scrollView.contentOffset.x / _cycleCollectionView.bounds.size.width - 1;
    
}

@end
#pragma mark - CollectionViewCell
@implementation HXCycleImageCell

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.cycleImage = [[UIImageView alloc] initWithFrame:self.bounds];
        [self.contentView addSubview:_cycleImage];
        self.label = [[UILabel alloc] initWithFrame:CGRectMake(0, self.bounds.size.height - 40, SCREEN_WIDTH - 100, 40)];
        self.label.textColor = [UIColor whiteColor];
        self.label.font = [UIFont systemFontOfSize:22.0 weight:0.5];
        [self.cycleImage addSubview:self.label];
        self.video = [[UIImageView alloc] init];
        self.video.frame = CGRectMake(10, self.bounds.size.height - 90, 50, 50);
        self.video.image = [UIImage imageNamed:@"LZImg_FirstPage_Play_L"];
        [self addSubview:self.video];
        self.video.alpha = 0;
    }
    return self;
}
- (void)layoutSubviews {
    [super layoutSubviews];
    
}
@end
